package doc

import (
	"api/config/code"
	"fmt"
	"gitee.com/dreamwood/ez"
	"gitee.com/dreamwood/ez-twig/twig"
	"gitee.com/dreamwood/ez/server"
	"reflect"
	"strings"
)

var twigger *twig.Twig

func init() {
	twigger = new(twig.Twig)
	twigger.ConfRoot = ez.GLB.AppRoot
	twigger.ConfPhpBinPath = "php"
	twigger.ConfCacheDir = "/var/twig"
	twigger.ConfIndexPath = "/twig/php"
	twigger.ConfTwigPath = "/libs/doc/views/twig"
	twigger.ConfDev = false
	twigger.ConfNumPipes = 5
	twigger.Init()
}

func init() {
	server.Do(&server.Router{Url: `/_doc/_config.json`}, GetConfigAction)
	server.Do(&server.Router{Url: `/_doc/_config.html`}, GetConfigViewAction)
	server.Do(&server.Router{Url: `/_doc/_config_tables.json`}, GetTableChoiceAction)
	server.Do(&server.Router{Url: `/_doc/_config_fields.json`}, GetFilesAction)
}

func GetConfigAction(operation *server.Operation) {

	data := make(map[string]interface{})
	data["code"] = code.Success
	data["message"] = "OK"
	data["data"] = ModelJsonConfig.Get()
	operation.JsonOut(data)
}

func GetConfigViewAction(operation *server.Operation) {
	html := twigger.Render("/dbconfig/db.twig", ez.M{
		"conf": ModelJsonConfig.Get(),
	})
	operation.Output.Html(html)
}

func GetTableChoiceAction(operation *server.Operation) {
	config := ModelJsonConfig.Get()
	type Item struct {
		Key   string `json:"key"`
		Value string `json:"value"`
	}
	list := make([]Item, 0)
	JsonData := make(map[string]interface{})
	for _, m := range config {
		table, ok := m["table"].(map[string]interface{})
		if ok {
			list = append(list, Item{fmt.Sprintf("%s.%s", table["path"], table["name"]), fmt.Sprintf("%s.%s", table["path"], table["name"])})
		} else {
			println(reflect.TypeOf(m["table"]).String())
		}
	}
	JsonData["lists"] = list
	data := make(map[string]interface{})
	data["code"] = code.Success
	data["message"] = "OK"
	data["data"] = JsonData
	operation.JsonOut(data)
}
func GetFilesAction(operation *server.Operation) {
	tableAndPath := operation.Get("table").IsString()
	tmp := strings.Split(tableAndPath, ".")
	tableName := tmp[1]
	tablePath := tmp[0]
	config := ModelJsonConfig.Get()
	type Item struct {
		Key   string `json:"key"`
		Value string `json:"value"`
	}
	list := make([]Item, 0)
	JsonData := make(map[string]interface{})
	data := make(map[string]interface{})
	for _, m := range config {
		table, ok := m["table"].(map[string]interface{})
		if ok {
			if tableName == table["name"].(string) && tablePath == table["path"].(string) {
				JsonData["lists"] = table["fields"]
				data["code"] = code.Success
				data["message"] = "OK"
				data["data"] = JsonData
				operation.JsonOut(data)
				return
			}
			list = append(list, Item{table["name"].(string), table["name"].(string)})
		} else {
			println(reflect.TypeOf(m["table"]).String())
		}
	}
	JsonData["lists"] = make([]interface{}, 0)
	data["code"] = code.Success
	data["message"] = "OK"
	data["data"] = JsonData
	operation.JsonOut(data)
}
